# -*- coding: utf-8 -*-
"""
ECharts 柱状图组件
"""
from pyecharts.charts import Bar
from pyecharts import options as opts
from .xy_chart_base import TgXYChartBase
import pandas as pd
import warnings

class TgBarChart(TgXYChartBase):
    """ECharts 柱状图组件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 样式配置
        self._is_stacked = False
        self._is_horizontal = False
        self._show_labels = True
        self._show_datazoom = True
        self._compact_mode = False
        
        # 轴配置
        self._x_label_rotate = -15
        self._x_label_font_size = 12
        self._y_label_font_size = 12
        
        # 图例配置
        self._legend_orient = "horizontal"
        self._legend_pos_top = "5%"
        self._legend_pos_left = "center"

    def set_stacked(self, enabled=True):
        """设置是否堆叠显示"""
        self._is_stacked = enabled
        self.update_chart()
        return self

    def set_horizontal(self, enabled=True):
        """设置是否水平显示"""
        self._is_horizontal = enabled
        self.update_chart()
        return self

    def set_labels(self, show=True):
        """设置是否显示数值标签"""
        self._show_labels = show
        self.update_chart()
        return self

    def set_datazoom(self, enabled=True):
        """设置是否显示数据缩放控件"""
        self._show_datazoom = enabled
        self.update_chart()
        return self

    def set_compact_mode(self, enabled=True):
        """设置紧凑模式（小字体、小尺寸）"""
        self._compact_mode = enabled
        if enabled:
            self._x_label_font_size = 10
            self._y_label_font_size = 10
            self._legend_pos_top = "3%"
        else:
            self._x_label_font_size = 12
            self._y_label_font_size = 12
            self._legend_pos_top = "5%"
        self.update_chart()
        return self

    def set_x_label_style(self, rotate=-15, font_size=None):
        """设置X轴标签样式"""
        self._x_label_rotate = rotate
        if font_size is not None:
            self._x_label_font_size = font_size
        self.update_chart()
        return self

    def set_legend_style(self, orient="horizontal", pos_top="5%", pos_left="center"):
        """设置图例样式"""
        self._legend_orient = orient
        self._legend_pos_top = pos_top
        self._legend_pos_left = pos_left
        self.update_chart()
        return self

    def create_chart(self) -> Bar:
        """创建图表实例"""
        init_opts = None
        if self._compact_mode:
            init_opts = opts.InitOpts(width="100%", height="280px")
        return Bar(init_opts=init_opts) if init_opts else Bar()

    def update_chart(self):
        """
        更新图表
        """
        if self.df is None or self.x_axis_column is None or not self.y_axis_columns:
            return

        chart = self.create_chart()
        x_data = self.df[self.x_axis_column].tolist()
        chart.add_xaxis(x_data)

        for col in self.y_axis_columns:
            add_yaxis_kwargs = {
                "series_name": col,
                "y_axis": self.df[col].tolist(),
                "label_opts": opts.LabelOpts(is_show=self._show_labels)
            }
            if self._is_stacked:
                add_yaxis_kwargs["stack"] = "stack1"
            chart.add_yaxis(**add_yaxis_kwargs)

        if self._is_horizontal:
            chart.reversal_axis()

        global_opts = {
            "title_opts": opts.TitleOpts(title=self.chart_title),
            "xaxis_opts": opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(
                    rotate=self._x_label_rotate,
                    font_size=self._x_label_font_size
                ),
                interval=max(1, len(x_data) // 20) if len(x_data) > 20 else 0
            ),
            "yaxis_opts": opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(
                    formatter="{value}",
                    font_size=self._y_label_font_size
                )
            ),
            "legend_opts": opts.LegendOpts(
                orient=self._legend_orient,
                pos_top=self._legend_pos_top,
                pos_left=self._legend_pos_left,
                item_width=20 if self._compact_mode else 25,
                item_height=10 if self._compact_mode else 14
            )
        }

        if self._show_datazoom and len(x_data) > 10:
            global_opts["datazoom_opts"] = opts.DataZoomOpts()

        chart.set_global_opts(**global_opts)
        self.render_chart(chart)

    def clear(self):
        """Clear chart content and reset internal state"""
        if hasattr(self, 'webview') and self.webview is not None:
            try:
                self.webview.setHtml("<html><head><meta charset='utf-8'></head><body></body></html>")
            except Exception:
                pass
        self.chart = None
        self.df = None
        self.x_axis_column = None
        self.y_axis_columns = []
